class Solution
{
public:
    int maximumSwap(int num)
    {
        string numStr = to_string(num);
        int n = numStr.size();
        int maxNumIdx = n - 1;
        int firstLessLeftIdx = -1;
        int greaterRightWithLessLeftExistsIdx = n - 1;
        for (int i = n - 1; i >= 0; --i)
        {
            if (numStr[i] > numStr[maxNumIdx])
            {
                maxNumIdx = i;
            }
            else if (numStr[i] < numStr[maxNumIdx])
            {
                firstLessLeftIdx = i;
                greaterRightWithLessLeftExistsIdx = maxNumIdx;
            }
        }
        if (firstLessLeftIdx != -1)
        {
            swap(numStr[firstLessLeftIdx], numStr[greaterRightWithLessLeftExistsIdx]);
        }

        return stoi(numStr);
    }
};